package hoyo.zqy.log.aspect;

import hoyo.zqy.log.annotation.LogAnnotation;
import hoyo.zqy.log.domain.LogDomain;
import hoyo.zqy.log.service.ILogService;
import hoyo.zqy.log.util.HttpContextUtils;
import hoyo.zqy.log.util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    private ILogService logService;

    @Pointcut("@annotation(hoyo.zqy.log.annotation.LogAnnotation)")
    public void pt(){}

    @Around("pt()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        long beginTime =System.currentTimeMillis();

        Object result=joinPoint.proceed();

        long time=System.currentTimeMillis()-beginTime;
        recordLog(joinPoint,time);
        return result;
    }

    private void recordLog(ProceedingJoinPoint joinPoint, long time) {
        LogDomain logDomain = new LogDomain();
        MethodSignature signature=(MethodSignature)joinPoint.getSignature();
        Method method=signature.getMethod();
        LogAnnotation logAnnotation=method.getAnnotation(LogAnnotation.class);
        String module = logAnnotation.module();
        log.info("单位:{}",module);
        String operater = logAnnotation.operater();
        log.info("operation:{}",operater);

        String className=joinPoint.getTarget().getClass().getName();
        String methodName=signature.getName();
        String res_method=className+"."+methodName+"()";
        log.info("请求方法:{}",res_method);

        Object[] args=joinPoint.getArgs();
        String params= args.toString();
        log.info("params:{}",params);

        HttpServletRequest request= HttpContextUtils.getHTTPServletRequest();
        String ipAddr = IpUtils.getIpAddr(request);
        log.info("ip:{}",ipAddr);

        log.info("请求时间:{} ms",time);

        logDomain.setIP(ipAddr);
        logDomain.setModule(module);
        if(params.length()<50){
            logDomain.setParams(params);
        }
        logDomain.setRes_method(res_method);
        logDomain.setOperation(operater);
        logService.save(logDomain);
    }
}
